package com.tanhua.server.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.enums.TypeEnum;
import com.tanhua.common.mapper.JournalMapper;
import com.tanhua.common.pojo.Journal;
import com.tanhua.server.vo.JournalVo;
import com.tanhua.server.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JournalService {
    @Autowired
    private JournalMapper journalMapper;

    public PageResult queryJournalList(Integer page, Integer pagesize, String sortProp, String sortOrder) {
        QueryWrapper<Journal> queryWrapper = new QueryWrapper<>();
        if (StrUtil.equals("descending",sortOrder)){
            queryWrapper.orderByDesc(sortProp);
        }else if (StrUtil.equals("ascending",sortOrder)){
            queryWrapper.orderByAsc(sortProp);
        }
        IPage<Journal> journalIPage = journalMapper.selectPage(new Page<>(page, pagesize), queryWrapper);

        List<JournalVo> journalList=new ArrayList<>();
        for (Journal record : journalIPage.getRecords()) {
            JournalVo JournalVo=new JournalVo();
            JournalVo.setId(record.getId());
            JournalVo.setName(record.getName());
            JournalVo.setRouter(record.getRouter());
            JournalVo.setDescribes(record.getDescribes());
            TypeEnum[] values = TypeEnum.values();
            for (TypeEnum value : values) {
                if (StrUtil.equals(value.getValue()+"",record.getType())){
                    JournalVo.setType(value.getType());
                }
            }
            String format = DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm:ss");
            JournalVo.setCreated(format);

            journalList.add(JournalVo);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setItems(journalList);
        return pageResult;
    }
}
